/*
 * (C) APUE
 * set a limit time in read
 * Note: in my ubuntu, read will restart from a slow system call(here I means read) by interupt
 * so we use setjmp/longjmp to quit the read
 */
#include "apue.h"
#include <setjmp.h>

static void sig_alrm(int);
static jmp_buf jmpbuffer;
int main()
{
	char line[MAXLINE];
	int n;
	

	/* set signal handler of SIGALRM */
	if (signal(SIGALRM, sig_alrm) == SIG_ERR)
		err_quit("signal error");

	/* setjmp for interupting read time out */
	if (setjmp(jmpbuffer) != 0)
		err_quit("read time out");

	/* set timer */
	alarm(5);

	/* read from stdin */
	if ((n = read(STDIN_FILENO, line, MAXLINE)) < 0)
		err_quit("read error");

	/* turn off the timer */
	alarm(0);

	/* output to stdout */
	if (write(STDOUT_FILENO, line, n) != n)
		err_quit("write error");

	exit(0);
}

static void sig_alrm(int signo)
{
	longjmp(jmpbuffer, 1);
	//return;	/* nothing to do, just return to interupt the read */
}
